package de.slothsoft.commons;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class Combination<E> implements Iterator<List<E>> {
	private E head;
	private List<E> tail;
	private Iterator<List<E>> iterator;

	public Combination(List<E> list) {
		if (list.isEmpty()) {
			this.head = null;
			this.tail = null;
			this.iterator = this;
		} else {
			this.head = list.get(0);
			this.tail = list.subList(1, list.size());
			this.iterator = new Combination<E>(this.tail);
		}
	}

	@Override
	public boolean hasNext() {
		return (this.tail != null) || (this.iterator == this)
				|| ((this.iterator != null) && (this.iterator.hasNext()));
	}

	@Override
	public List<E> next() {
		if (!hasNext() || (this.iterator == null)) {
			throw new NoSuchElementException();
		}
		if (this.iterator == this) {
			this.iterator = null;
			return Collections.emptyList();
		}
		if (!this.iterator.hasNext()) {
			this.iterator = new Combination<E>(this.tail);
			this.tail = null;
		}
		List<E> rv = new ArrayList<E>();
		if (this.tail == null) {
			rv.add(this.head);
		}
		rv.addAll(this.iterator.next());
		return rv;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}
